package com.wwdx.utils;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * @author liguoliang
 */
public class HttpSender {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * url 应用地址，类似于http://ip:port/msg/
     * account 账号
     * password 密码
     * extno 扩展码
     */
    private String url,account,password,extno;

    public HttpSender() {
        this.url = ConstantHolder.Constant.SMS_URL;
        this.account = ConstantHolder.Constant.SMS_ACCOUNT;
        this.password = ConstantHolder.Constant.SMS_PASSWORD;
        this.extno = ConstantHolder.Constant.SMS_EXTNO;
    }

    /**
     * 发送验证码
     * @param mobile 手机号码，多个号码使用","分割
     * @param content 短信内容
     * @return 短信相关参数
     */
	public String batchSend(String mobile, String content) {
		HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
		GetMethod method = new GetMethod();
        InputStream in = null;
        ByteArrayOutputStream baos = null;
		try {
			URI base = new URI(url, false);
			method.setURI(new URI(base, "HttpBatchSendSM", false));
			method.setQueryString(new NameValuePair[]{
					new NameValuePair("account", account),
					new NameValuePair("pswd", password),
					new NameValuePair("mobile", mobile),
                    //是否需要状态报告，需要true，不需要false
					new NameValuePair("needstatus", "true"),
					new NameValuePair("msg", content),
					new NameValuePair("extno", extno),
			});
			int result = client.executeMethod(method);
			if (result == HttpStatus.SC_OK) {
                in = method.getResponseBodyAsStream();
                baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				baos.flush();
				return URLDecoder.decode(baos.toString(), "UTF-8");
			}
		}catch (IOException e){
			logger.error("错误信息：{}",e.getMessage());
		} finally {
			method.releaseConnection();
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(baos);
		}
        return null;
	}
}